package com.sky.service.User.Address;

import com.sky.constant.BaseContext;

import com.sky.entity.Address;
import com.sky.mapper.AddressMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static com.sky.constant.IsDefaultConstant.DEFAULT_ADDRESS;
import static com.sky.constant.IsDefaultConstant.NO_DEFAULT_ADDRESS;

/**
 * @Author 褚金龙
 * @Date 2024/9/27 19:59
 */
@Service
public class AddressServiceImpl implements AddressService{
   @Autowired
   private AddressMapper addressMapper;
    /**
     * 保存收货地址
     * @return
     */
    @Override
    public void saveAddress(Address address) {
        Long userId = BaseContext.getCurrentId();
        address.setUserId(userId);
        addressMapper.saveAddress(address);

    }

    /**
     * 查询所有收货地址
     * @return
     */
    @Override
    public List<Address> addressList() {
       List<Address> list= addressMapper.addressList();
        return list;
    }

    /**
     * 根据id查询地址
     * @param id
     * @return
     */
    @Override
    public Address getById(Long id) {
        Long userId = BaseContext.getCurrentId();
        Address address=  addressMapper.getById(id,userId);
        return address;
    }

    /**
     *根据id userId修改收货地址
     * @param address
     */
    @Override
    public void updateAddress(Address address) {
        addressMapper.updateAddress(address);
    }

    @Override
    public void deleteAddress(Long id) {
        Long userId = BaseContext.getCurrentId();
        addressMapper.deleteAddress(id,userId);
    }

    /**
     * 设置默认收货地址
     * @param id
     */
    @Transactional
    @Override
    public void defaultAddress(Long id) {
        //1.先把所有地址全部修改成非默认地址
        Long userId = BaseContext.getCurrentId();
        Address address=new Address();
        address.setUserId(userId);
        address.setId(id);
        address.setIsDefault(NO_DEFAULT_ADDRESS);
      addressMapper.defaultAddress(address);

      //2.在设置对应的id的为默认收货地址，因为默认地址只允许有一个
        address.setIsDefault(DEFAULT_ADDRESS);
        addressMapper.updateAddress(address);

    }

    /**
     * 查询默认地址
     * @return
     */
    @Override
    public List<Address> getDefaultAddress() {
        Long userId = BaseContext.getCurrentId();
       List<Address> addressList= addressMapper.getDefaultAddress(DEFAULT_ADDRESS,userId);
        return addressList;
    }


}
